#define _XOPEN_SOURCE  600
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

int main()
{
    char rx = 0;
    char rxbuf[128] = {0};
    char txbuf[256] = {0};
    int master = 0;
    int c = 0;
    int i = 0;
    
    master = posix_openpt(O_RDWR); // gnome-terminal
    
    if( master > 0 ) {
        grantpt(master);
        unlockpt(master);
        
        printf("Slave: %s\n", ptsname(master));
        
        while( (c = read(master, &rx, 1)) == 1 ) {
            if( rx == '\r' ) {
                rxbuf[i] = 0;
                sprintf(txbuf, "from slave: %s\r", rxbuf); // show on screen
                write(master, txbuf, strlen(txbuf)); // keyboard input
                i = 0;
            } else {
                rxbuf[i++] = rx;
            }
        }
        
        close(master);
    } else {
        printf("create pty error...\n");
    }
    
    return 0;
}
